package v1

import (
	"net/http"
	"strings"
	"time"

	"github.com/tungyao/cedar"
	"github.com/tungyao/spruce-light"
)

var (
	H *spruce.Hash
)

func init() {
	H = spruce.CreateHash(4096)
}
func PageAppIndex(writer http.ResponseWriter, request *http.Request, co *cedar.Core) {
	co.View().Assign("Name", str(cedar.Random())).Render()
}

func PageAppRegister(writer http.ResponseWriter, request *http.Request, co *cedar.Core) {
	co.View().Render()
}
func AppRegister(writer http.ResponseWriter, request *http.Request, co *cedar.Core) {
	// 拦截次数
	if n := H.Get(byt(strings.Split(request.RemoteAddr, ":")[0])); n != nil {
		if n.(int) >= 1 {
			Json(writer).Error("Multiple requests")
			return
		}
	} else {
		H.Set(byt(strings.Split(request.RemoteAddr, ":")[0]), 1, 3600)
	}
	if len(request.FormValue("appid")) < 16 || len(request.FormValue("secret")) < 32 {
		Json(writer).Error("app or secret length not enough")
		return
	}
	_, err := DB.Exec("insert into app set app=?,secret=?,create_time=?", request.FormValue("appid"), request.FormValue("secret"), time.Now().Unix())
	if err != nil {
		co.Json().Error("db error")
	} else {
		co.Json().Success(map[string]string{"execute": "success"})
	}
}
